﻿using JuCheap.Core.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace JuCheap.Core.Services.AppServices
{
    public class DefaultModelEntityMapper : IModelEntityMapper
    {
        private readonly IServiceProvider _serviceProvider;

        public DefaultModelEntityMapper(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public TDestination Map<TSource, TDestination>(TSource source)
        {
            if (source == null)
            {
                return default(TDestination);
            }

            using (var scope = _serviceProvider.CreateScope())
            {
                var specificMapper = scope.ServiceProvider.GetService<IModelEntityMapper<TSource, TDestination>>();

                if (specificMapper != null)
                {
                    return specificMapper.Map(source);
                }
            }

            return AutoMap<TSource, TDestination>(source);
        }

        public TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
        {
            if (source == null || destination == null)
            {
                return default(TDestination);
            }

            using (var scope = _serviceProvider.CreateScope())
            {
                var specificMapper = scope.ServiceProvider.GetService<IModelEntityMapper<TSource, TDestination>>();

                if (specificMapper != null)
                {
                    return specificMapper.Map(source, destination);
                }
            }

            return AutoMap(source, destination);
        }

        protected virtual TDestination AutoMap<TSource, TDestination>(TSource source)
        {
            throw new NotImplementedException();
        }

        protected virtual TDestination AutoMap<TSource, TDestination>(TSource source, TDestination destination)
        {
            throw new NotImplementedException();
        }
    }
}
